<template>
  <div>
    <el-button type="primary" @click="clickAddProduct">新增产品</el-button>
    <el-table :data="data.productTableData" style="width: 100%">
      <el-table-column prop="productId" label="产品编号" width="180"> </el-table-column>
      <el-table-column prop="name" label="产品名" width="180"> </el-table-column>
      <el-table-column prop="status" :formatter="data.statusFormatter" label="产品状态" width="180"> </el-table-column>
      <el-table-column  label="操作">
        <template #default="scope">
          <el-button
              type="text"
              size="small"
              @click="clickProductDetail(scope.row)"
          >产品详情</el-button
          >
          <el-button
              type="text"
              size="small"
              @click="clickProcessDetail(scope.row)"
          >加工过程</el-button
          >
          <el-button
              type="text"
              size="small"
              @click="clickFinishProcess(scope.row)"
          >完成加工</el-button
          >


        </template>
      </el-table-column>
    </el-table>
    <el-dialog
        v-model="data.addProductVisible"
        title="原料上链"
    >
      <el-form :model="data.addProductForm">
        <el-form-item label="产品编号" :label-width="data.formLabelWidth">
          <el-input v-model="data.addProductForm.productId" disabled></el-input>
        </el-form-item>
        <el-form-item label="产品名" :label-width="data.formLabelWidth">
          <el-input v-model="data.addProductForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="产品品类" :label-width="data.formLabelWidth">
          <el-input v-model="data.addProductForm.productType" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="原农产品ID" :label-width="data.formLabelWidth">
          <el-input v-model="data.addProductForm.cropId" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
          <span class="dialog-footer">
            <el-button @click="data.addProcessVisible = false">取消</el-button>
            <el-button type="primary" @click="handleAddProduct">确认</el-button>
          </span>
      </template>
    </el-dialog>
    <el-dialog
        v-model="data.finishProcessVisible"
        title="完成加工"
    >
      <el-form :model="data.finishProcessForm">
        <el-form-item label="产品编号" :label-width="data.formLabelWidth">
          <el-input v-model="data.finishProcessForm.productId" disabled></el-input>
        </el-form-item>
        <el-form-item label="出厂日期" :label-width="data.formLabelWidth">
          <el-input v-model="data.finishProcessForm.time"></el-input>
        </el-form-item>
        <el-form-item label="质检报告" :label-width="data.formLabelWidth">
         <UploadPic @getUploadHash="getHash"></UploadPic>
        </el-form-item>

      </el-form>
      <template #footer>
          <span class="dialog-footer">
            <el-button @click="data.finishProcessVisible = false">取消</el-button>
            <el-button type="primary" @click="handleFinishProcess">确认</el-button>
          </span>
      </template>
    </el-dialog>
    <el-dialog
        v-model="data.productDetailVisible"
        title="产品详情"
    >
      <el-descriptions
          class="margin-top"
          title="产品详情"
          :column="2"
          border
      >
        <template v-for="(value,key) in data.productDetailData">
          <el-descriptions-item v-if="key!=1" :label="data.productDetailFormatter[key]">{{ value }}</el-descriptions-item>

        </template>
        <el-descriptions-item label="质检报告">
            <el-button type="primary" @click="checkCertification(data.productDetailData)">查看</el-button>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
    <el-dialog v-model="data.certificationVisible">
      <img class="certification" :src="data.certificationSrc" />
    </el-dialog>


  </div>
</template>

<script>
import {onMounted, reactive} from "vue";
import {v1 as uuidv1} from "uuid";
import {
  func_addProduct, func_finishProcess,
  func_getAddress,

  func_getUserInfo, func_getUserProduct,
  func_getUserRole
} from "../../../api/etherneum/api";
import {useStore} from "vuex";
import {useRouter} from "vue-router";
import {getYMD} from "../../../utils/TimeStamp";
import {ElMessage} from "element-plus";
import UploadPic from "@/components/UploadPic/index";
import ipfsAPI from "ipfs-api";
const ipfs = ipfsAPI({ host: "49.234.138.61", port: "5001", protocol: "http" });
export default {
  name: "Process",
  components:{
    UploadPic
  },
  setup(){
    const data=reactive({
      processTableData:[],
      addProcessVisible:false,
      addProcessForm:{
        processId:'',
        cropId:''
      },
      formLabelWidth:'140px',

      productTableData:[
        {},
      ],
      addProductVisible:false,
      addProductForm:{
        productId:'',
        cropId:'',
        productType:''
      },

      finishProcessVisible:false,
      finishProcessForm:{},

      productDetailVisible:false,
      productDetailData:[],
      productDetailFormatter:{
        0:'产品编号',
        1:'质检报告',
        2:'产品状态',
        3:'原农产品ID',
        4:'产品名称',
        5:'出厂时间',
        6:'产品品类',
        7:'负责人'
      },
      statusFormatter:(row)=>{
        if (row.status==0) return '待加工'
        else return '加工完成'
      },
      certificationVisible:false,
      certificationSrc:''
    })
    const store=useStore();
    const router=useRouter();
    const clickAddProduct=()=>{
      if (data.curUserInfo.role!=1&&data.curUserInfo.role!=4){
        ElMessage.error('无权限')
        return
      }
      data.addProductVisible=true
      data.addProductForm.productId=uuidv1()
    }

    const handleAddProduct=()=>{



      func_addProduct(data.addProductForm)
      data.addProductVisible=false
    }

    const getAddress = async () => {
      const address = await func_getAddress();
      if (address) {
        store.commit("app/SET_ADDRESS", address);
        let role = await func_getUserRole(address);
        store.commit("app/SET_ROLE", role);
        console.log("getUser address=" + address + " role=" + role);
        data.address = address;
        data.currentRole = role;
        data.curUserInfo = await func_getUserInfo(data.address);
        console.log("cur:" + data.curUserInfo.requestRole);
      }
    };

    const clickProcessDetail=(row)=>{
      let productId=row.productId
      console.log('row:',row.productId)
      store.commit("crops/UPDATE_STATE_VALUE", {
        productId: {
          value: productId,
          session: true
        },
      });
      let url=router.resolve({path: `/Function/processDetail/${productId}`})
      window.open(url.href, '_blank');
    }

    const clickFinishProcess=(row)=>{
      if (row.status==1){
        ElMessage.error('加工已完成')
        return
      }
      data.finishProcessVisible=true
      data.finishProcessForm.productId=row.productId
      data.finishProcessForm.cropId=row.cropId

      data.finishProcessForm.time=getYMD(new Date())
    }
    const handleFinishProcess=()=>{
      if (!data.finishProcessForm.certification){
        ElMessage.error('图片未上传')
        return
      }
      func_finishProcess(data.finishProcessForm)
      data.finishProcessVisible=false
    }

    const clickProductDetail=(row)=>{
      data.productDetailData=row
      data.productDetailVisible=true
    }
    const handleProductDetail=()=>{
      data.productDetailVisible=false
    }

    const getHash=(hash)=>{
      data.finishProcessForm.certification=hash
    }

    const checkCertification=async (row)=>{
      let hash=row.certification
      data.loading=true
      console.log('certification:',row.certification)
      ipfs.get(hash, async (err, result) => {
        console.log('here')
        if (err) throw err;
        let binaryData = [];
        binaryData.push(result[0].content.buffer);
        data.certificationSrc= window.URL.createObjectURL(new Blob(binaryData))
        console.log('src=',data.certificationSrc)
        data.loading=false
      });

      data.certificationVisible=true
    }

    onMounted(()=>{
      getAddress().then(async () => {
        data.productTableData=await func_getUserProduct(data.address)
        console.log(data.productTableData)

      });
      ethereum.on("accountsChanged", () => {
        getAddress();
      });
    })
    return{
      data,
      clickAddProduct,
      handleAddProduct,
      clickProcessDetail,
      clickFinishProcess,
      handleFinishProcess,
      clickProductDetail,
      handleProductDetail,
      getHash,
      checkCertification
    }
  }
}
</script>

<style lang="scss" scoped>
.certification{
  width: 800px;
}
</style>